package com.yuyou.tas.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yuyou.tas.admin.service.IAuthResourceService;
import com.yuyou.tas.admin.service.IAuthUserSectionService;
import com.yuyou.tas.admin.service.IAuthUserService;
import com.yuyou.tas.admin.vo.req.ReqAuthUserAdd;
import com.yuyou.tas.admin.vo.req.ReqAuthUserUpdate;
import com.yuyou.tas.admin.vo.req.ReqSysAuthUserAdd;
import com.yuyou.tas.admin.vo.req.ReqSysAuthUserUpdate;
import com.yuyou.tas.admin.vo.resp.RespAuthRoleResource;
import com.yuyou.tas.service.api.admin.dto.AuthUserDTO;
import com.yuyou.tas.service.api.admin.dto.SysAuthUserDTO;
import com.yuyou.tas.service.api.admin.dto.TeacherDTO;
import com.yuyou.tas.util.bean.*;
import com.yuyou.tas.util.tool.SpringValidateUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value="AuthResourceController",description="用户管理接口")
@Validated
@RestController
@RequestMapping(value="/api/authUser")
public class AuthUserController extends BaseController{

    @Autowired
    private IAuthUserService authUserService;

    @Autowired
    private IAuthResourceService authResourceService;

    @Autowired
    private IAuthUserSectionService authUserSectionService;

    @ApiOperation(value="账号管理(机构)")
    @RequestMapping(value="/findAuthUserPage", method = { RequestMethod.POST })
    public ReturnResult<AuthUserDTO> findAuthUserPage(@Validated @ModelAttribute PageParams pageParams,
                                                      @ApiParam(value = "人员状态：0：在职，1：离职")@RequestParam(value = "workStatus", required = false)Integer workStatus,
                                                      @ApiParam(value = "用户名或账户")@RequestParam(value = "keyword", required = false) String keyword,
                                                      @ApiParam(value = "人员类型：1：教师 2：教研 3：教务 4：班主任（班主任） 5：其他（外部班主任）")@RequestParam(value = "type", required = false) Integer type,
                                                      HttpServletRequest request){
        LoginRedisObj loginObj = getUserObj(request);
        Long organizationId = loginObj.getOrganizationId();
        Boolean isSystem = loginObj.getIsSystem();


        Map<String, Object> conditions = new HashMap<>();
        Pagination<AuthUserDTO> queryPgn = new Pagination<>();

        if(type != null){
            conditions.put("type" , type);
        }

        conditions.put("isSystem", isSystem);
        conditions.put("authOrganizationId", organizationId);
        conditions.put("workStatus", workStatus);
        conditions.put("keyword", null != keyword ? keyword.trim() : keyword);
        queryPgn.setConditions(conditions);
        queryPgn.setPageParams(pageParams);
        int total = authUserService.findAuthUserPageCount(queryPgn);
        queryPgn.setTotal(total);
        queryPgn.toBePage();
        if(total > 0){
            queryPgn.setTotal(total);
            List<AuthUserDTO> list = authUserService.findAuthUserPageList(queryPgn);
            queryPgn.setList(list);
        }

        return ReturnResult.success(queryPgn);
    }

    @ApiOperation(value="新增帐号(机构)")
    @RequestMapping(value="/addAuthUser", method = RequestMethod.POST )
    public ReturnResult<ResBoolSimpleInfo> addAuthUser(@ApiParam(value = "新增帐号json字符串")@RequestParam(value = "authUserAddJsonStr")String authUserAddJsonStr,
                                                       HttpServletRequest request){

        LoginRedisObj loginObj = getUserObj(request);

        ReqAuthUserAdd reqAuthUserAdd = JSONObject.parseObject(authUserAddJsonStr, new TypeReference<ReqAuthUserAdd>(){});
        ResBoolSimpleInfo<String> res= SpringValidateUtil.check(reqAuthUserAdd);
		if(!res.isSuccess()){
            return ReturnResult.returnRes(res.isSuccess(), res.getMessage(), res.getData());
		}
        res = authUserService.insertAuthUser(reqAuthUserAdd, loginObj);

        return ReturnResult.returnRes(res.isSuccess(), res.getMessage(), res.getData());
    }


    @ApiOperation(value="修改资料(机构)")
    @RequestMapping(value="/updateAuthUser", method = { RequestMethod.POST })
    public ReturnResult<ResBoolSimpleInfo> updateAuthUser(@ApiParam(value = "修改资料json字符串")@RequestParam(value = "authUserUpdateJsonStr")String authUserUpdateJsonStr,
                                                          HttpServletRequest request){

        LoginRedisObj loginObj = getUserObj(request);

        ReqAuthUserUpdate reqAuthUserUpdate = JSONObject.parseObject(authUserUpdateJsonStr, new TypeReference<ReqAuthUserUpdate>(){});
        ResBoolSimpleInfo<String> res= SpringValidateUtil.check(reqAuthUserUpdate);
        if(!res.isSuccess()){
            return ReturnResult.returnRes(res.isSuccess(), res.getMessage(), res.getData());
        }
        res = authUserService.updateAuthUser(reqAuthUserUpdate, loginObj);
        return ReturnResult.returnRes(res.isSuccess(), res.getMessage(), res.getData());
    }


    @ApiOperation(value="帐号详情")
    @RequestMapping(value="/authUserDetail", method = { RequestMethod.POST })
    public ReturnResult<AuthUserDTO> authUserDetail(@NotNull(message="id不能为空") @RequestParam(value = "id")Long id){

        AuthUserDTO authUserDTO = authUserService.findAuthUser(id);
        return ReturnResult.success(authUserDTO);
    }

    @ApiOperation(value="账号管理(系统)")
    @RequestMapping(value="/findSysAuthUserPage", method = { RequestMethod.POST })
    public ReturnResult<SysAuthUserDTO> findSysAuthUserPage(@Validated @ModelAttribute PageParams pageParams,
                                                         @ApiParam(value = "帐号状态  0:已失效 1:正常")@RequestParam(value = "status", required = false)Integer status,
                                                         @ApiParam(value = "用户名或账户")@RequestParam(value = "keyword", required = false) String keyword,
                                                         HttpServletRequest request){
        LoginRedisObj loginObj = getUserObj(request);
        Boolean isSystem = loginObj.getIsSystem();

        Map<String, Object> conditions = new HashMap<>();
        Pagination<SysAuthUserDTO> queryPgn = new Pagination<>();

        conditions.put("isSystem", isSystem);
        conditions.put("status", status);
        conditions.put("keyword", null != keyword ? keyword.trim() : keyword);
        queryPgn.setConditions(conditions);
        queryPgn.setPageParams(pageParams);
        int total = authUserService.findSysAuthUserPageCount(queryPgn);
        queryPgn.setTotal(total);
        queryPgn.toBePage();
        if(total > 0){
            queryPgn.setTotal(total);
            List<SysAuthUserDTO> list = authUserService.findSysAuthUserPageList(queryPgn);
            queryPgn.setList(list);
        }

        return ReturnResult.success(queryPgn);
    }


    @ApiOperation(value="更改帐号状态")
    @RequestMapping(value="/updateStatus", method = RequestMethod.POST )
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "id", paramType="query", required = true),
                        @ApiImplicitParam(name = "status", value = "帐号状态  0:禁用 1:正常", paramType="query", required = true)}
    )
    public ReturnResult<ResBoolSimpleInfo> updateStatus(@NotNull(message="id 不能为空") Long id,
                                                        @NotNull(message="status 不能为空") Integer status){

        ResBoolSimpleInfo res = authUserService.updateStatus(id, status);//
        return ReturnResult.returnRes(res.isSuccess(), res.getMessage(), res.getData());
    }


    @ApiOperation(value="新增帐号(系统)")
    @RequestMapping(value="/addSysAuthUser", method = RequestMethod.POST )
    public ReturnResult<ResBoolSimpleInfo> addSysAuthUser(@Validated @ModelAttribute ReqSysAuthUserAdd reqSysAuthUserAdd,
                                                          HttpServletRequest request){

        LoginRedisObj loginObj = getUserObj(request);
        ResBoolSimpleInfo res = authUserService.insertSysAuthUser(reqSysAuthUserAdd, loginObj);
        return ReturnResult.returnRes(res.isSuccess(), res.getMessage(), res.getData());
    }

    @ApiOperation(value="更新帐号(系统)")
    @RequestMapping(value="/updateSysAuthUser", method = RequestMethod.POST )
    public ReturnResult<ResBoolSimpleInfo> updateSysAuthUser(@Validated @ModelAttribute ReqSysAuthUserUpdate reqSysAuthUserUpdate,
                                                             HttpServletRequest request){

        LoginRedisObj loginObj = getUserObj(request);
        ResBoolSimpleInfo res = authUserService.updateSysAuthUser(reqSysAuthUserUpdate, loginObj);
        return ReturnResult.returnRes(res.isSuccess(), res.getMessage(), res.getData());
    }

    @ApiOperation(value = "老师列表")
    @RequestMapping(value = "/teacherList" ,method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "dataSubject", value = "科目id", paramType="query", required = false),
                        @ApiImplicitParam(name = "baseSectionId", value = "年级 id", paramType="query", required = false),
                        @ApiImplicitParam(name = "keyword", value = "关键字", paramType="query", required = false),
                        @ApiImplicitParam(name = "lessonClassId", value = "班级id", paramType="query", required = false),
                        @ApiImplicitParam(name = "type", value = "老师类型  0:主讲老师，1：代课老师", paramType="query", required = false)
    })
    public ReturnResult<List<TeacherDTO>> teacherList(Long dataSubject, Long baseSectionId, String keyword, Long lessonClassId, Integer type, HttpServletRequest request){
        LoginRedisObj loginObj = getUserObj(request);

        List<TeacherDTO> teacherList = authUserService.findTeacherList(null, baseSectionId, null == keyword ? keyword : keyword.trim(), loginObj.getOrganizationId(), lessonClassId, type);
        return ReturnResult.success(teacherList);
    }

    @ApiOperation("获取配置(权限)")
    @RequestMapping(value = "/config", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<RespAuthRoleResource>> config(HttpServletRequest request) {
        LoginRedisObj loginObj = getUserObj(request);
        List<RespAuthRoleResource> authResourceList = authResourceService.findAuthResourceByUserIdFromCache(loginObj.getUserId());
        return ReturnResult.success(authResourceList);
    }

}
